package com.meatball.dji.common.mqtt.handler.request.handler

import com.alibaba.fastjson.JSON
import com.meatball.dji.common.mqtt.handler.request.data.dto.OrganizationGetParams
import com.meatball.dji.common.mqtt.handler.request.data.vo.OrganizationGetReplyParams
import com.meatball.dji.common.mqtt.router.MessageHandler
import com.meatball.dji.common.mqtt.topic.TopicConstants
import com.meatball.dji.common.util.interpolate
import org.eclipse.paho.client.mqttv3.MqttClient
import org.eclipse.paho.client.mqttv3.MqttMessage

/**
 * TODO 查询设备绑定对应的组织信息
 *
 * @property mqttClient
 *
 * @author 张翔宇
 * @since 2024年4月22日
 */
class OrganizationGetHandler(private val mqttClient: MqttClient) : MessageHandler {
    override fun handle(message: String) {
        // 解析参数
        val params = JSON.parseObject(message, OrganizationGetParams::class.java)
        // 组装返回参数
        val result = createResultParams(params)

        // 返回信息
        val topic = TopicConstants.REQUESTS_REPLY_MESSAGE_STRUCT.interpolate(TopicConstants.GATEWAY_SN to params.gateway)
        val msg = MqttMessage(JSON.toJSONString(result).toByteArray())

        // QoS0，At most once，至多一次；
        // QoS1，At least once，至少一次；
        // QoS2，Exactly once，确保只有一次。
        msg.qos = 2

        // 推送消息
        mqttClient.publish(topic, msg)
    }

    /**
     * TODO 创建返回参数
     *
     * @param params 入参
     * @return 出参
     */
    private fun createResultParams(params: OrganizationGetParams) =
        OrganizationGetReplyParams(
            tid = params.tid,
            bid = params.bid,
            gateway = params.gateway,
            method = params.method,
            data = OrganizationGetReplyParams.Data(
                result = 0,
                output = OrganizationGetReplyParams.Data.Output(
                    organizationName = "测试组织"
                )
            )
        )
}